package com.xdl.moudle.utils.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 利用MD5加密
 * 
 */
public class MD5 {

	public static final String key = "xdl$xdl@0904";

	public static void main(String[] args) throws Exception {
		String message = "age=21&pageIndex=1&uid=12";
		String key = "xdl$xdl@0904";
		String encrypt = encrypt(message, key);
		System.out.println(message + "&source=" + encrypt);
		
		System.out.println(validate(message, encrypt));
	}

	public static boolean validate(String message, String source) {
		try {
			String encrypt = encrypt(message, key);
			return encrypt.equals(source);
		} catch (Exception e) {
			return false;
		}
	}

	public static String encrypt(String message, String key) throws Exception {
		return encrypt(message + "&key=" + key);
	}

	/**
	 * 加密方法
	 * 
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public static String encrypt(String data) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		byte[] src_bytes = data.getBytes("utf-8");
		md5.update(src_bytes);
		byte[] resultBytes = md5.digest();
		String temp = byte2Hex(resultBytes);
		String s = "";
		String tmp[] = temp.split(":");
		for (int i = 0; i < tmp.length; i++) {
			s = s + tmp[i];
		}

		return s;
	}

	/**
	 * 辅助方法
	 * 
	 * @param b
	 * @return
	 */
	public static String byte2Hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			// 整型数stmp，每个元素都与0xFF做与运算，得出的还是自己，0的话就返回0
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				hs = hs + "0" + stmp;
			} else {
				hs = hs + stmp;
			}
			if (n < b.length - 1)
				hs = hs + ":";
		}
		return hs.toUpperCase();
	}
}
